from django.contrib.auth.hashers import make_password
from rest_framework import serializers, views
from .models import *


class PermissionSerializer(serializers.HyperlinkedModelSerializer):
    # 使用 HyperlinkedModelSerializer 需要定义相关的url
    class Meta:
        model = Permission
        fields = '__all__'


class GroupSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Group
        fields = '__all__'


class UserSerializer(serializers.HyperlinkedModelSerializer):  # use url to link group
    gender_dis = serializers.CharField(source='get_gender_display', read_only=True)

    class Meta:
        # TODO: read_only write_only
        model = User
        fields = ['url', 'username', 'email', 'gender_dis', 'blog_set', 'comment_set']
        # fields = ['url', 'username', 'email', 'get_gender_display', 'blog_set', 'comment_set']
        # fields = '__all__'

        # extra_kwargs = {
        #     'get_gender_display': {
        #         'read_only': True,
        #     }
        # }

        # read_only_fields = ['get_gender_display']

    def create(self, validated_data: dict):
        username = validated_data.pop('username')
        email = validated_data.pop('email')
        password = validated_data.pop('password')

        return User.objects.create_user(username, email, password)

    def update(self, instance, validated_data):
        password = validated_data.pop('password', None)
        if password:
            instance.set_password(password)
        return super().update(instance, validated_data)

